<?php
// +----------------------------------------------------------------------
// | 简易CMS
// +----------------------------------------------------------------------
// | Copyright (C) 2010 Hoping Software Studio.
// +----------------------------------------------------------------------
// | Version $Id$
// +----------------------------------------------------------------------

namespace CMS\behavior;
use think\Hook;


// 初始化钩子信息
class InitHookBehavior {

    // 行为扩展的执行入口必须是run
    public function run(&$content){
        if(defined('BIND_MODULE') && BIND_MODULE === 'Install') return;

        defined('DS') || define('DS', DIRECTORY_SEPARATOR);
        defined('ROOT_PATH') || define('ROOT_PATH', dirname(dirname(dirname(__file__))) . DS);
        if (!isset($_SERVER['HTTPS']))
            $_SERVER['HTTPS'] = 'off';

        $_SERVER['PHP_SELF'] = htmlspecialchars($_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['PHP_SELF']);
        $_SERVER['basefilename'] = basename($_SERVER['PHP_SELF']);

        define('CMS_ROOT', substr($_SERVER['PHP_SELF'], 0, -strlen($_SERVER['basefilename'])));
        define('CMS_URL', strtolower(($_SERVER['HTTPS'] == 'on' ? 'https' : 'http') .
                '://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/') + 1)));

        define('MY_QUERY_ERROR', 10501);

        define('FUNC_PATH', APP_PATH . 'common'.DS);


        // 异常处理类
        set_exception_handler('CMS\Core::exception_handle');
        // 自定义错误处理函数，设置后 error_reporting 将失效。因为要保证 ajax 输出格式，所以必须触发 error_handle
        set_error_handler('CMS\Core::error_handle');
        register_shutdown_function('CMS\Core::fatalError');

        $data = S('hooks');
        if(!$data){
            $hooks = \think\Db::name('Hooks')->column('name, addons');
            foreach ($hooks as $key => $value) {
                if ($value) {
                    $aModel = \think\Db::name('Addons');
                    $aModel = $aModel->where('status', 1);
                    $names = explode(',', $value);
                    if(count($names)==1){
                        $map = $value;
                    } else {
                        $map = array('IN', $names);
                    }
                    $aModel = $aModel->where(array('name' => $map));
                    $data = $aModel->column('id,name');
                    if($data){
                        $addons = array_intersect($names, $data);
                        Hook::add($key,array_map('get_addon_class',$addons));
                    }
                }
            }
            S('hooks',Hook::get());
        }else{
            Hook::import($data,false);
        }
    }
}